using UnityEngine;
using QFramework;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace ProjectIndieFarm
{
    public partial class ShopItemTemplate : ViewController
    {
        public EasyEvent OnBuyClick = new();
        public BindableProperty<bool> IsInteractable = new(false);
        void Start()
        {
            Btn.GetOrAddComponent<ButtonGesture>().OnPress.Register(() =>
            {
                if (!Btn.interactable) return;
                OnBuyClick.Trigger();
            }).UnRegisterWhenGameObjectDestroyed(gameObject);

            IsInteractable.RegisterWithInitValue(interactable =>
            {
                if (interactable)
                {
                    Btn.interactable = true;
                    Btn.GetComponentInChildren<Text>().ColorAlpha(1.0f);
                }
                else
                {
                    Btn.interactable = false;
                    Btn.GetComponentInChildren<Text>().ColorAlpha(0.6f);
                    Btn.GetComponent<ButtonGesture>().EndPressEvent();
                }
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
        }

        public class ButtonGesture : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IBeginDragHandler
        {
            public EasyEvent OnPress = new EasyEvent();
            private IActionController mCurrentAction;

            private void OnEnable()
            {
                if (mCurrentAction != null)
                {
                    EndPressEvent();
                }
            }
            private void OnDisable()
            {
                if (mCurrentAction != null)
                {
                    EndPressEvent();
                }
            }
            public void OnPointerDown(PointerEventData eventData)
            {
                OnPress.Trigger();

                mCurrentAction = ActionKit.Sequence()
                    .Delay(0.5f)
                    .Repeat(r =>
                    {
                        r.Delay(0.05f)
                        .Callback(() => OnPress.Trigger());
                    }).Start(this, () =>
                    {
                        mCurrentAction = null;
                    });
            }

            public void OnPointerUp(PointerEventData eventData)
            {
                EndPressEvent();
            }
            public void OnBeginDrag(PointerEventData eventData)
            {
                EndPressEvent();
            }


            public void EndPressEvent()
            {
                if (mCurrentAction != null)
                {
                    mCurrentAction.Deinit();
                    mCurrentAction = null;
                }
            }
        }
    }

}